'use strict';

const BaseService = require('./base');
const modelName = 'User';
class RouterService extends BaseService {
  constructor(ctx) {
    super(ctx, modelName);
  }
  async getPage(where, page, pageSize) {
    return await this.ctx.model[this.modelName].findAndCountAll({
      where,
      offset: pageSize * (page - 1),
      limit: pageSize,
      order: [
        // id 降序
        ['id', 'DESC'],
      ],
      include: [
        {
          model: this.ctx.model.Dept,
          as: 'dept'
        },
        {
          model: this.ctx.model.Role,
          as: 'role'
        }
      ]
    });
  }

  async login(username, password) {
    const user = await this.ctx.model[this.modelName].findOne({
      where: {
        username,
        password
      },
      include: [
        {
          model: this.ctx.model.Role,
          as: 'role'
        }
      ],
    });
    if (!user) {
      throw new Error('用户名或密码错误');
    }
    console.log('user',user)
    let menuList = null
    // 角色中的menu
    if (user.role) {
      let _menuList = await this.ctx.model.Menu.findAll({
        where: {
          id: user.role.menu.split(',')
        },
        raw: true
      })
      menuList = _menuList
    } else {
      if (user.type === 0) {
        menuList = []
      }
    }
    console.log('menuList',menuList)
    return {
      ...user.dataValues,
      menuList,
      token: 'token'
    };
  }
}


module.exports = RouterService;
